package com.rzico.sbl.ui.manager

import android.widget.ImageView
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityPickupReportBinding
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.PickReportData
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.PickupViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class PickupReportActivity : BaseActivity(R.layout.activity_pickup_report) {

    private val mBinding by lazy { ActivityPickupReportBinding.bind(getRootView()) }

    private val mStationList = ArrayList<FilterData>()
    private val mCupboardList = ArrayList<FilterData>()
    private lateinit var mStationId: String
    private lateinit var mStationName: String
    private var mCupboardId = ""
    private var mCupboardName = ""
    private var mDateMode = "4"
    private var mBeginDate = getFirstDate()
    private var mEndDate = getEndDate()

    override fun getViewModel() = get<PickupViewModel>()

    override fun initData() {
        initTitle(title = "销量统计")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关统计记录！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<PickReportData>(R.layout.item_pickup_report) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_pick_name, bean.productName)
                            text(
                                R.id.item_pick_sation,
                                bean.shopName + bean.cabinetName.ifNotEmpty { "($it)" }
                            )
                            text(R.id.item_pick_stock, bean.stock)
                            text(R.id.item_pick_sale, bean.quantitySum)
                            text(R.id.item_pick_money, bean.amountSum.formatDecimal())

                            with<ImageView>(R.id.item_pick_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            clicked {
                                startActivityEx<PickupReportOrderActivity>(
                                    "keyWord" to bean.productName,
                                    "stationId" to mStationId,
                                    "stationName" to mStationName,
                                    "cupboardId" to mCupboardId,
                                    "cupboardName" to mCupboardName,
                                    "dateMode" to mDateMode,
                                    "beginDate" to mBeginDate,
                                    "endDate" to mEndDate
                                )
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    override fun initListener() {
        mBinding.apply {
            mStationId = intent.getExtra("stationId")
            mStationName = intent.getExtra("stationName")

            mStationId.notEmpty {
                pickStation.text = mStationName
                pickStation.setTextColor(getColorEx(R.color.colorAccent))
                pickStationArrow.setImageResource(R.mipmap.icon_member02)
            }

            getViewModel()
                .mUncheckTimeList[3]
                .isChecked = true
            pickTime.text = getViewModel().mUncheckTimeList[3].hint

            pickStationLl.oneClick {
                (mStationList.size < 2)
                    .conditionElse(
                        actionTrue = {
                            getStationList {
                                showStationDrop()
                            }
                        },
                        actionFalse = ::showStationDrop
                    )
            }

            pickCupboardLl.oneClick {
                getCupboardList { showCupboardDrop() }
            }

            pickTimeLl.oneClick {
                getViewModel()
                    .showDropTimeFilter(
                        getIContext(),
                        pickTime,
                        pickTimeArrow,
                        pickTop,
                        getViewModel().mUncheckTimeList
                    ) { bean ->

                        (bean.id != "7")
                            .condition {
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"
                            }

                        when (bean.id) {
                            "1" -> {
                                mDateMode = "1"
                                mBeginDate = getTodayDate()
                                mEndDate = getTodayDate()

                                updateList()
                            }

                            "2" -> {
                                mDateMode = "2"
                                mBeginDate = getBeforeDate()
                                mEndDate = getBeforeDate()

                                updateList()
                            }

                            "3" -> {
                                mDateMode = "3"
                                mBeginDate = getMondayDate()
                                mEndDate = getSundayDate()

                                updateList()
                            }

                            "4" -> {
                                mDateMode = "4"
                                mBeginDate = getFirstDate()
                                mEndDate = getEndDate()

                                updateList()
                            }

                            "5" -> {
                                mDateMode = "5"
                                mBeginDate = getBeforeFirstDate()
                                mEndDate = getBeforeEndDate()

                                updateList()
                            }

                            "6" -> {
                                mDateMode = "6"
                                mBeginDate = getYearFirstDate()
                                mEndDate = getYearEndDate()

                                updateList()
                            }

                            "7" -> {
                                showTimeRangeDialog(
                                    isCurrentDate = true,
                                    isAfterLimited = true,
                                    onResult = { start, end ->
                                        getViewModel()
                                            .mUncheckTimeList
                                            .forEach { it.isChecked = false }

                                        getViewModel()
                                            .mUncheckTimeList
                                            .last()
                                            .isChecked = true

                                        mDateMode = "7"
                                        mBeginDate = start
                                        mEndDate = end
                                        bean.name = "$mBeginDate ~ $mEndDate"
                                        pickTime.text = bean.name

                                        updateList()
                                    }
                                )
                            }
                        }
                    }

            }
        }
    }

    /**
     * 自提站点筛选
     */
    private fun showStationDrop() {
        mBinding.apply {
            getViewModel()
                .showDropTimeFilter(
                    getIContext(),
                    pickStation,
                    pickStationArrow,
                    pickTop,
                    mStationList
                ) {
                    pickStation
                        .setTextColor(
                            getColorEx(
                                conditionIf(
                                    it.id.isEmpty(),
                                    R.color.black,
                                    R.color.colorAccent
                                )
                            )
                        )

                    pickStationArrow
                        .setImageResource(
                            conditionIf(
                                it.id.isEmpty(),
                                R.mipmap.icon_member01,
                                R.mipmap.icon_member02
                            )
                        )

                    (mStationId != it.id)
                        .condition {
                            mCupboardId = ""
                            mCupboardName = ""

                            pickCupboard.text = "自提柜"
                            pickCupboard
                                .setTextColor(
                                    getColorEx(R.color.black)
                                )

                            pickCupboardArrow
                                .setImageResource(R.mipmap.icon_member01)
                        }

                    mStationId = it.id
                    mStationName = conditionIf(it.id.isEmpty(), "", it.name)

                    updateList()
                }
        }
    }

    /**
     * 自提柜筛选
     */
    private fun showCupboardDrop() {
        mBinding.apply {
            getViewModel()
                .showDropTimeFilter(
                    getIContext(),
                    pickCupboard,
                    pickCupboardArrow,
                    pickTop,
                    mCupboardList
                ) {
                    pickCupboard
                        .setTextColor(
                            getColorEx(
                                conditionIf(
                                    it.id.isEmpty(),
                                    R.color.black,
                                    R.color.colorAccent
                                )
                            )
                        )

                    pickCupboardArrow
                        .setImageResource(
                            conditionIf(
                                it.id.isEmpty(),
                                R.mipmap.icon_member01,
                                R.mipmap.icon_member02
                            )
                        )

                    mCupboardId = it.id
                    mCupboardName = conditionIf(it.id.isEmpty(), "", it.name)

                    updateList()
                }
        }
    }

    /**
     * 自提站点列表
     */
    private fun getStationList(onFinish: () -> Unit) {
        getViewModel()
            .stationList(
                page = 0,
                keyWord = "",
                categoryId = "",
                pageSize = 1000,
                isLoading = true,
                onSuccess = { list ->
                    mStationList.clear()
                    mStationList.add(
                        FilterData(
                            "全部",
                            "",
                            "自提站点",
                            mStationId.isEmpty()
                        )
                    )

                    list.mapTo(mStationList) {
                        FilterData(
                            it.name.orEmpty(),
                            it.id,
                            it.name.orEmpty(),
                            mStationId.isNotEmpty() && it.id == mStationId
                        )
                    }

                    onFinish.invoke()
                }
            )
    }

    /**
     * 自提柜列表
     */
    private fun getCupboardList(onFinish: () -> Unit) {
        mStationId
            .isNotEmpty()
            .conditionElse(
                actionTrue = {
                    getViewModel()
                        .cupboardList(
                            page = 0,
                            keyWord = "",
                            shopId = mStationId,
                            pageSize = 1000,
                            isLoading = true,
                            onSuccess = { list ->
                                mCupboardList.clear()
                                mCupboardList.add(FilterData("全部", "", "自提柜", true))

                                list.mapTo(mCupboardList) {
                                    FilterData(it.name, it.id, it.name)
                                }

                                onFinish.invoke()
                            }
                        )
                },
                actionFalse = {
                    mCupboardList.clear()
                    mCupboardList.add(FilterData("全部", "", "自提柜", true))

                    onFinish.invoke()
                }
            )
    }

    /**
     * 押桶统计列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .reportList(
                page = index,
                shopId = mStationId,
                cupboardId = mCupboardId,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it.data)
                        it.data.notEmpty { pageNum++ }

                        mBinding
                            .apply {
                                pickSale.text = it.summary?.subQuantity.orEmpty("0")
                                pickMoney.text = it.summary?.subPrice.orEmpty("0.00")
                            }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}